use "data\out\estsample.dta", clear 


* forbruksgrupper - lav til høy 
gegen pre_forbruk = mean(exp(lnforbruk)) if month == 12 & day <= 7, by(maalepktnr)
gegen int pre_forbruk_ = cut(pre_forbruk) if pre_forbruk != ., group(4)
gegen int pre_forbruk_q = max(pre_forbruk_), by(maalepktnr)
drop pre_forbruk pre_forbruk_

fmerge m:1 maalepktnr using "data\in\maalepktnr_grunnkretsincome.dta", keep(match) nogenerate

* Total treatment dummy. Swithces on on first event day
g byte Ttotal = ((year == 2019 & month == 12 & day >= 10) | year == 2020) //after first event
replace Ttotal = 0 if Treat == 0 
egen Egroup = max(Effektpris), by(maalepktnr)
g byte Etotal = ((year == 2019 & month == 12 & day >= 10) | year == 2020) //after first event
replace Etotal = 0 if Egroup == 0 
foreach y in Etotal Ttotal {
g byte `y'elcar = `y'*elcar 
}


* all 
ivreghdfe lnforbruk c.temp##c.temp##c.temp temp_* ///
  (Etotal Etotalelcar = Ttotal Ttotalelcar), absorb(maalepktnr dato) cluster(maalepktnr)
est store tot
estadd ysumm
gunique maalepktnr if e(sample) & elcar == 1 
estadd scalar elcars = r(unique): tot`i'  


* IHD (in house display)
g byte wattmeter = inlist(stratgroups,2,5,8,11) == 1
forval i = 0/1 {
ivreghdfe lnforbruk c.temp##c.temp##c.temp temp_* ///
  (Etotal Etotalelcar = Ttotal Ttotalelcar) if wattmeter == `i', absorb(maalepktnr dato) cluster(maalepktnr)
est store tot_w`i'
estadd ysumm
gunique maalepktnr if e(sample) & elcar == 1 
estadd scalar elcars = r(unique): tot_w`i'  
}

* income 
forval i = 0(2)2 {
ivreghdfe lnforbruk c.temp##c.temp##c.temp temp_* ///
  (Etotal Etotalelcar = Ttotal Ttotalelcar) if income_q == `i' | income_q == `i' + 1, absorb(maalepktnr dato) cluster(maalepktnr)
est store tot_i`i'
estadd ysumm
gunique maalepktnr if e(sample) & elcar == 1 
estadd scalar elcars = r(unique): tot_i`i'  
}

* consumption 
forval i = 0(2)2 {
ivreghdfe lnforbruk c.temp##c.temp##c.temp temp_* ///
  (Etotal Etotalelcar = Ttotal Ttotalelcar) if pre_forbruk_q == `i' | pre_forbruk_q == `i' + 1, absorb(maalepktnr dato) cluster(maalepktnr)
est store tot_c`i'
estadd ysumm
gunique maalepktnr if e(sample) & elcar == 1 
estadd scalar elcars = r(unique): tot_c`i'  
}


estout tot tot_i0 tot_i2 tot_w1 tot_w0 tot_c0 tot_c2 using "table_4_results_total.txt", replace type ///
  keep(E* ) /// Peak shoulder *elcar
  cells(b( fmt(3)) se(par fmt(3)) _star) mlabels(, titles) ///
  collabels(none) legend /// indicate(temp)
  varlabels(TPE TP TNPE TNP) starlevels(* 0.10 ** 0.05 *** 0.01) ///
  stats(ymean r2 N, fmt(3 3 0 0)) style(tex)
